package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.Entrust;




@Repository
public class HouseEntrustDao extends BaseDao<Entrust,String> {

    private static final Log log = LogFactory.getLog(HouseEntrustDao.class);
    @Autowired
	SessionFactory sessionFactory;
    
    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    public void persist(Entrust transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(Entrust persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public Entrust merge(Entrust detachedInstance) {
        try {
            Entrust result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public Entrust getById(String  id) {
        try {
            Entrust instance = entityManager.find(Entrust.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    /** 根据 参数获取  */
    @SuppressWarnings("unchecked")
	public Entrust getByParam(Entrust entrust) {
        try {
        	StringBuffer sqld = new StringBuffer("from Entrust  where 1=1 ");
          if(!StringUtils.isEmpty(entrust.getHouseId())){
	            sqld.append(" and houseId="+entrust.getHouseId());
	         }
	         Query query = entityManager.createQuery(sqld.toString());         
            List<Entrust> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByParam fail",e);
            throw e;
        }
    }
        

    @SuppressWarnings("unchecked")
	public List<Entrust> getList(Map param, int pageSize, int offset) {
        StringBuffer sql = new StringBuffer("select a.*, u.sex, u.phone 'u_phone'  from lj_house_entrust a left join lj_user u on a.userId = u.userId where 1=1 ");
        //设置参数
        if(!StringUtils.isEmpty(param.get("searchText"))){
        	sql.append(" and (a.phone like '%"+param.get("searchText").toString()+"%' or a.nickName like  '%"+param.get("searchText").toString()+"%' )");
        }
        sql.append(" order by createTime desc");
    	SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(offset).setMaxResults(pageSize).list();
    }
    
    
    public long getListCount(Map param) {
        try {
            StringBuffer sql = new StringBuffer("select a.*, u.sex, u.phone 'u_phone'  from lj_house_entrust a left join lj_user u on a.userId = u.userId where 1=1 ");
            //设置参数
            if(!StringUtils.isEmpty(param.get("phone"))){
            	sql.append(" and a.phone like:1 ");
            }
            if(!StringUtils.isEmpty(param.get("nickName"))){
                sql.append(" and u.nickName like:2 ");
            }
       
        	SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        	
            if(!StringUtils.isEmpty(param.get("phone"))){
            	query.setString("1",(String)param.get("phone"));
            }
            if(!StringUtils.isEmpty(param.get("nickName"))){
            	query.setString("2",(String)param.get("nickName"));
            }
        			
            return query.list().size();
           // return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return 0;
    }


}
